<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Room;
use App\Models\Dish;
use App\Services\DishService;
use App\Traits\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class DishController extends Controller
{
    use ApiResponse;

    protected DishService $dishService;

    public function __construct(DishService $dishService)
    {
        $this->dishService = $dishService;
    }

    /**
     * 获取房间菜品列表
     */
    public function getRoomDishes(Request $request, string $roomId): JsonResponse
    {
        $user = Auth::user();
        $room = Room::where('room_id', $roomId)->first();

        if (!$room) {
            throw new \App\Exceptions\BusinessException('房间不存在', 10001);
        }

        if (!$room->hasMember($user->id)) {
            throw new \App\Exceptions\BusinessException('无权限查看房间菜品', 10004);
        }

        try {
            if (!$room->menu) {
                return $this->success([
                    'dishes' => [],
                    'categories' => $this->getCategories(),
                    'message' => '房间暂无菜单'
                ]);
            }
            
            $dishes = $this->dishService->getMenuDishes($room->menu);
            $categories = $this->getCategories();

            return $this->success([
                'dishes' => $dishes->map(function ($dish) {
                    return [
                        'id' => $dish->id,
                        'name' => $dish->name,
                        'description' => $dish->description,
                        'image' => $dish->image,
                        'category' => $dish->category ? $dish->category->name : null,
                        'tags' => $dish->tags,
                        'flavors' => $dish->flavors,
                        'cooking_time' => $dish->cooking_time,
                        'is_featured' => $dish->is_featured,
                        'dish_source' => $dish->dish_source,
                        'creator' => $dish->creator ? $dish->creator->name : null,
                        'source_dish_id' => $dish->source_dish_id,
                    ];
                }),
                'categories' => $categories,
            ]);
        } catch (\Exception $e) {
            return $this->error('获取菜品列表失败：' . $e->getMessage(), 50001);
        }
    }

    /**
     * 搜索房间菜品
     */
    public function searchRoomDishes(Request $request, string $roomId): JsonResponse
    {
        $user = Auth::user();
        $room = Room::where('room_id', $roomId)->first();

        if (!$room) {
            throw new \App\Exceptions\BusinessException('房间不存在', 10001);
        }

        if (!$room->hasMember($user->id)) {
            throw new \App\Exceptions\BusinessException('无权限搜索菜品', 10004);
        }

        $request->validate([
            'keyword' => 'sometimes|string|max:100',
            'category_id' => 'sometimes|integer|exists:categories,id',
        ]);

        try {
            if (!$room->menu) {
                return $this->success([
                    'dishes' => [],
                    'message' => '房间暂无菜单'
                ]);
            }
            
            $dishes = $this->dishService->searchMenuDishes(
                $room->menu,
                $request->input('keyword'),
                $request->input('category_id')
            );

            return $this->success([
                'dishes' => $dishes->map(function ($dish) {
                    return [
                        'id' => $dish->id,
                        'name' => $dish->name,
                        'description' => $dish->description,
                        'image' => $dish->image,
                        'category' => $dish->category ? $dish->category->name : null,
                        'tags' => $dish->tags,
                        'flavors' => $dish->flavors,
                        'cooking_time' => $dish->cooking_time,
                        'is_featured' => $dish->is_featured,
                        'dish_source' => $dish->dish_source,
                        'creator' => $dish->creator ? $dish->creator->name : null,
                    ];
                })
            ]);
        } catch (\Exception $e) {
            return $this->error('搜索菜品失败：' . $e->getMessage(), 50001);
        }
    }

    /**
     * 添加自定义菜品到房间
     */
    public function addCustomDish(Request $request, string $roomId): JsonResponse
    {
        $user = Auth::user();
        $room = Room::where('room_id', $roomId)->first();

        if (!$room) {
            throw new \App\Exceptions\BusinessException('房间不存在', 10001);
        }

        if (!$room->hasMember($user->id)) {
            throw new \App\Exceptions\BusinessException('无权限添加菜品', 10004);
        }

        $request->validate([
            'name' => 'required|string|max:100',
            'description' => 'nullable|string|max:500',
            'category_id' => 'nullable|exists:categories,id',
            'image' => 'nullable|string',
            'tags' => 'nullable|array',
            'flavors' => 'nullable|array',
            'cooking_time' => 'nullable|integer|min:1',
            'is_featured' => 'sometimes|boolean',
        ]);

        try {
            if (!$room->menu) {
                throw new \App\Exceptions\BusinessException('房间暂无菜单', 10001);
            }
            
            $dish = $this->dishService->addCustomDishToMenu($room->menu, $request->all(), $user->id);

            return $this->success([
                'dish' => $dish->load(['category', 'creator'])
            ], '菜品添加成功');
        } catch (\Exception $e) {
            return $this->error('添加菜品失败：' . $e->getMessage(), 50001);
        }
    }

    /**
     * 修改房间菜品
     */
    public function updateDish(Request $request, string $roomId, int $dishId): JsonResponse
    {
        $user = Auth::user();
        $room = Room::where('room_id', $roomId)->first();

        if (!$room) {
            throw new \App\Exceptions\BusinessException('房间不存在', 10001);
        }

        if (!$room->menu) {
            throw new \App\Exceptions\BusinessException('房间暂无菜单', 10001);
        }

        $dish = Dish::where('menu_id', $room->menu_id)
            ->where('id', $dishId)
            ->first();

        if (!$dish) {
            throw new \App\Exceptions\BusinessException('菜品不存在', 20005);
        }

        if (!$room->hasMember($user->id)) {
            throw new \App\Exceptions\BusinessException('无权限修改菜品', 20003);
        }

        $request->validate([
            'name' => 'sometimes|string|max:100',
            'description' => 'nullable|string|max:500',
            'category_id' => 'nullable|exists:categories,id',
            'image' => 'nullable|string',
            'tags' => 'nullable|array',
            'flavors' => 'nullable|array',
            'cooking_time' => 'nullable|integer|min:1',
            'is_available' => 'sometimes|boolean',
            'is_featured' => 'sometimes|boolean',
        ]);

        try {
            $updatedDish = $this->dishService->updateMenuDish($dish, $request->all());

            return $this->success([
                'dish' => $updatedDish->load(['category', 'creator', 'sourceDish'])
            ], '菜品修改成功');
        } catch (\Exception $e) {
            return $this->error('修改菜品失败：' . $e->getMessage(), 50001);
        }
    }

    /**
     * 删除房间菜品
     */
    public function deleteDish(Request $request, string $roomId, int $dishId): JsonResponse
    {
        $user = Auth::user();
        $room = Room::where('room_id', $roomId)->first();

        if (!$room) {
            throw new \App\Exceptions\BusinessException('房间不存在', 10001);
        }

        if (!$room->menu) {
            throw new \App\Exceptions\BusinessException('房间暂无菜单', 10001);
        }

        $dish = Dish::where('menu_id', $room->menu_id)
            ->where('id', $dishId)
            ->first();

        if (!$dish) {
            throw new \App\Exceptions\BusinessException('菜品不存在', 20005);
        }

        if (!$room->hasMember($user->id)) {
            throw new \App\Exceptions\BusinessException('无权限删除菜品', 20003);
        }

        try {
            $this->dishService->deleteMenuDish($dish);
            return $this->success([], '菜品删除成功');
        } catch (\Exception $e) {
            return $this->error('删除菜品失败：' . $e->getMessage(), 50001);
        }
    }

    /**
     * 获取用户的自定义菜品
     */
    public function getUserCustomDishes(Request $request): JsonResponse
    {
        $user = Auth::user();
        
        try {
            $dishes = $this->dishService->getUserCustomDishes($user->id);
            
            return $this->success([
                'dishes' => $dishes->map(function ($dish) {
                    return [
                        'id' => $dish->id,
                        'name' => $dish->name,
                        'description' => $dish->description,
                        'category' => $dish->category ? $dish->category->name : null,
                        'image' => $dish->image,
                        'tags' => $dish->tags,
                        'flavors' => $dish->flavors,
                        'cooking_time' => $dish->cooking_time,
                        'is_featured' => $dish->is_featured,
                        'is_public' => $dish->is_public,
                        'created_at' => $dish->created_at,
                    ];
                })
            ]);
        } catch (\Exception $e) {
            return $this->error('获取自定义菜品失败：' . $e->getMessage(), 50001);
        }
    }

    /**
     * 创建用户自定义菜品
     */
    public function createUserCustomDish(Request $request): JsonResponse
    {
        $user = Auth::user();
        
        $request->validate([
            'name' => 'required|string|max:100',
            'description' => 'nullable|string|max:500',
            'category_id' => 'nullable|exists:categories,id',
            'image' => 'nullable|string',
            'tags' => 'nullable|array',
            'flavors' => 'nullable|array',
            'cooking_time' => 'nullable|integer|min:1',
            'is_public' => 'sometimes|boolean',
            'is_featured' => 'sometimes|boolean',
        ]);

        try {
            $dish = $this->dishService->createUserCustomDish($request->all(), $user->id);
            
            return $this->success([
                'dish' => $dish->load(['category'])
            ], '自定义菜品创建成功');
        } catch (\Exception $e) {
            return $this->error('创建自定义菜品失败：' . $e->getMessage(), 50001);
        }
    }

    /**
     * 复制菜品到房间
     */
    public function copyDishToRoom(Request $request, string $roomId, int $dishId): JsonResponse
    {
        $user = Auth::user();
        $room = Room::where('room_id', $roomId)->first();

        if (!$room) {
            throw new \App\Exceptions\BusinessException('房间不存在', 10001);
        }

        if (!$room->hasMember($user->id)) {
            throw new \App\Exceptions\BusinessException('无权限添加菜品', 10004);
        }

        $sourceDish = Dish::find($dishId);
        if (!$sourceDish) {
            throw new \App\Exceptions\BusinessException('源菜品不存在', 20005);
        }

        try {
            if (!$room->menu) {
                throw new \App\Exceptions\BusinessException('房间暂无菜单', 10001);
            }
            
            $dish = $this->dishService->copyDishToMenu($sourceDish, $room->menu, $user->id);
            
            return $this->success([
                'dish' => $dish->load(['category', 'creator', 'sourceDish'])
            ], '菜品复制成功');
        } catch (\Exception $e) {
            return $this->error('复制菜品失败：' . $e->getMessage(), 50001);
        }
    }

    private function getCategories(): array
    {
        $categories = \App\Models\Category::active()->ordered()->get(['id', 'name', 'slug', 'description']);
        
        $result = [
            ['id' => 'all', 'name' => '全部', 'slug' => 'all', 'description' => '所有菜品']
        ];

        foreach ($categories as $category) {
            $result[] = [
                'id' => $category->id,
                'name' => $category->name,
                'slug' => $category->slug,
                'description' => $category->description,
            ];
        }

        return $result;
    }
}